package ups.MapParse;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Image {
	private Size 	_size;
	private int[] 	_bitmap;
	
	public Image( File imageFile ) throws Exception {
		BufferedImage buffImage = _loadImage( imageFile );
		_bitmap = new int[ buffImage.getWidth() * buffImage.getHeight() ]; 
		buffImage.getRGB( 0, 0, buffImage.getWidth(), buffImage.getHeight(), _bitmap, 0, buffImage.getWidth() );
		_size = new Size( buffImage.getWidth(), buffImage.getHeight() );
	}
	public Image( int[] bitmap, Size size ) {
		_bitmap = bitmap;
		_size = size;
	}
	
	public Size getSize() {
		return _size;
	}
	
	public int pixelAtPoint( Point point ) {
	//	System.out.println( "Looking at point " + point.toString() + " in image" + this.toString() );
		return _bitmap[ point.y * getSize().width + point.x ];
	}
	
	public boolean matches( Image image ) {
		if( ! (this.getSize().equals( image.getSize() ))) { return false; }
		
		int X, Y;
		for( X = 0; X < this.getSize().width; X++ ){
			for( Y = 0; Y < this.getSize().height; Y++ ){
				Point p = new Point( X, Y);
				if( this.pixelAtPoint( p ) != image.pixelAtPoint( p )) {
					return false;
				}
			}
		}
		
		return true;
	}
	
	public boolean matchesRegion( Image image, Rect imageRect ) {
		//System.out.println( this.toString() );
	//	System.out.println( image.toString() );
	//	System.out.println( imageRect.toString() );
		if(!( this.getSize().width == imageRect.size.width &&
			this.getSize().height == imageRect.size.height )) {
			return false;
		}
		int X, Y;
		for( X = 0; X < this.getSize().width; X++ ) {
			for( Y = 0; Y < this.getSize().height; Y++ ) {
				Point sourcePoint = new Point( X, Y );
				Point regionPoint = new Point( imageRect.origin.x + X, imageRect.origin.y + Y);
				if( this.pixelAtPoint( sourcePoint ) != image.pixelAtPoint( regionPoint )) {
					return false;
				}
			}
		}
		return true;
	}

	private static BufferedImage _loadImage( File imageFile ) throws Exception {
		BufferedImage image = null;
		try {
			image = ImageIO.read( imageFile );
		} catch ( IOException e ) {
			System.out.println( "Failed Loading Image: " + e.toString() +  " File: " +  imageFile.toString() );
			throw( e );
		} catch ( Exception ioex ) {
			System.out.println(  "Failed Loading Image " + ioex.toString() + " File: " +  imageFile.toString() );
			throw( ioex );
		}
		
		return image;
	}
	
	public String toString() {
		return "Image: " + this.getSize().toString() + " bitmap: " + _bitmap;
	}
}
